package com;

import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HttpHandlerThread2 implements Runnable {
	private Socket socket;

	public HttpHandlerThread2(Socket client) {
		socket = client;
		new Thread(this).start();
	}

	public void run() {
		try {
			// 读取客户端数据
			InputStreamReader is = new InputStreamReader(socket.getInputStream());
			char[] bs = new char[2048];
			StringBuilder msg = new StringBuilder();
			// 如果10毫秒还没有数据，则视同没有新的数据了。
			// 因为有Keep-Alive的缘故，浏览器可能不主动断开连接的。
			// 实际应用，会根据协议第一行是GET还是 POST确定。
			socket.setSoTimeout(10);
			//
			// 此处读入请求数据并做相应的处理
			//
			int len = -1;
			try {
				while ((len = is.read(bs)) != -1) {
					msg.append(bs, 0, len);
				}
			} catch (Exception ex) {
				// ex.printStackTrace();
			}
			String data=msg.toString().split("\r\n\r\n")[1];
			data = Aes.Decrypt(data, Main.txmy);

			MsgObj obj = MsgObj.fromJson(data);
			String resmsg = "";
			if (!obj.getType().equals("3") && !obj.getType().equals("4")) {
				MsgHandler.sendMsg(obj);
				resmsg = "1";
			} else if (obj.getType().equals("4")) {
				resmsg = "1";
			} else {
				String url=Main.getUrl();
				resmsg = url == null ? "0" : url;
			}
			
			byte[] resbyte=resmsg.getBytes();

			OutputStream out = socket.getOutputStream();
			out.write("HTTP/1.1 200 OK\r\n".getBytes());
			out.write("Server: JSP2/1.0.27\r\n".getBytes());
			out.write("Access-Control-Allow-Origin: *\r\n".getBytes());
			out.write("Cache-Control: no-cache\r\n".getBytes());
			
			SimpleDateFormat sdf = new SimpleDateFormat();
			out.write(("Date: " + (sdf.format(new Date())) + "\r\n").getBytes());
			out.write("Content-Type: text/html\r\n".getBytes());
			out.write(("Content-Length: "+resbyte.length+"\r\n").getBytes());
			out.write("Connection: Keep-Alive\r\n".getBytes());
			out.write("\r\n".getBytes());
			out.write(resbyte);

			out.flush();
			out.close();
			is.close();
		} catch (Exception e) {
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (Exception e) {
					socket = null;
				}
			}
		}
	}
}